/*
This software is distributed under the Simplified BSD License:

Copyright (c) 2008, Chris Venter <chris.venter@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
    	this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
    	this list of conditions and the following disclaimer in the documentation 
    	and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
DAMAGE.
*/
#ifndef GENERIK_POSTGRES_H
#define GENERIK_POSTGRES_H

/** \file postgres.h
This file defines a generik::database wrapper class for the libpq C-interface to PostgreSQL.
*/

#include <postgresql/libpq-fe.h>
#include <sys/select.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

#include "../threads.h"
#include "../database.h"
#include "../osutils.h"

#include "../tracing.h"

namespace generik
{

	/** A wrapper class for the libpq C-interface to PostgreSQL.
	
	It acts as both a templated SQL interface to run queries on the
	database, as well as a generik::emitter which listens for specific 
	notifications from the database.
	
	The listener/emitter functionality runs in a seperate thread which
	blocks on waiting for the notifies from the database. It will exit
	when sent a SIGUSR1 signal via pthread_kill().
	*/
	struct postgres
	: database
	{
		generik::mutex mutex;
		PGconn* connection;
		int socket;
	
		postgres(const std::string& connectionstring)
		: mutex("postgres")
		{
			GENERIK_TRACER;
			open(connectionstring);
		}
	
		postgres()
		: mutex("postgres")
		, connection(0)
		, socket(-1)
		{
			GENERIK_TRACER;
		}
	
		~postgres()
		{
			GENERIK_TRACER;
			close();
		}
	
		void open(const std::string& connectionstring)
		{
			GENERIK_TRACER;
			connection = PQconnectdb(connectionstring.c_str());
			if (!connection)
			{
				GENERIK_ERROR("connection failed");
				//exit(-1);
			}
			else
			{
				GENERIK_TRACE("connection succeeded");
				socket = PQsocket(connection);
				GENERIK_TRACE_VALUE(socket);
				start_listen();
			}
		}
	
		void close()
		{
			GENERIK_TRACER;
			if (connection)
			{
				// stop the listener thread
				stop_listen();
				// mutex
				mutex.lock();
				PQfinish(connection);
				mutex.unlock();
			}
			connection = 0;
		}
		
		PGresult* process(const std::string& cmd)
		{
			mutex.lock();
			PGresult* result = PQexec(connection, cmd.c_str());
			if (PQflush(connection) != 0)
			{
				GENERIK_TRACER;
				GENERIK_ERROR("Error flushing the postgres connection: "<<PQerrorMessage(connection));
			}
			mutex.unlock();

			if (!result)
			{
				GENERIK_TRACER;
				GENERIK_TRACE("["<<cmd<<"] failed: "<<PQresultErrorMessage(result));
				result = 0;
			}
			else if (!parse_result(result))
			{
				GENERIK_TRACER;
				GENERIK_TRACE("error running SQL");
				PQclear(result);
				result = 0;
			}
			return result;
		}
	
		void runquery(const std::string& cmd, callback cb, void* object)
		{
			PGresult* result = process(cmd);
			if (result)
			{
				int nrows = PQntuples(result);
				for (int i = 0; i < nrows; ++i)
				{
					int nfields = PQnfields(result);
					char* values[nfields];
					for (int j = 0; j < nfields; ++j) values[j] = PQgetvalue(result, i, j);
					(*cb)(nfields, values, object);
				}
				PQclear(result);
			}
		}
		
		void listen(const std::string& table)
		{
			GENERIK_TRACER;
			std::string command = "listen \"" + table + "\"";
			execute(command);
		}
		void unlisten(const std::string& table)
		{
			GENERIK_TRACER;
			std::string command = "unlisten \"" + table + "\"";
			execute(command);
		}
		void notify(const std::string& table)
		{
			GENERIK_TRACER;
			std::string command = "notify \"" + table + "\"";
			execute(command);
		}
	
		/// The listen() thread redirection starter function
		static void* listen(void* object)
		{
			((postgres*)object)->listen();
			return 0;
		}
	
		bool running;
		pthread_t tid;
		
		/** The installed signal handler that waits for SIGUSR1
		*/
		static void signal_handler(int signum)
		{
			GENERIK_TRACER;
			GENERIK_TRACE("got signal ["<<signum<<"]");
		}
		/** This utility function installs the signal_handler() to wait
		for SIGUSR1.
		*/
		void install_signal_handler(int signal, void(*handler)(int))
		{
			struct sigaction new_action;
			new_action.sa_handler = handler;
  			sigemptyset(&new_action.sa_mask);
  			new_action.sa_flags = 0;
  			sigaction(SIGUSR1, &new_action, NULL); 
		}
		
		/** Starts the listen() thread.
		*/
		void start_listen()
		{
			GENERIK_TRACER;
  			install_signal_handler(SIGUSR1, &signal_handler);
			running = true;
			pthread_create(&tid, 0, listen, this);
		}
		
		/** Stops the listen() thread.
		*/
		void stop_listen()
		{
			GENERIK_TRACER;
			running = false;
			pthread_kill(tid, SIGUSR1);
			pthread_join(tid, 0);
		}
		void consume()
		{
			REM_GENERIK_TRACER;
			mutex.lock();
			if (!PQconsumeInput(connection))
			{
				GENERIK_TRACER;
				GENERIK_ERROR("Error consuming Postgres input: "<<PQerrorMessage(connection));
			}
			mutex.unlock();
		}
		
		bool waitforinput()
		{
			//GENERIK_TRACER;
			fd_set readfds, errorfds;
			FD_ZERO(&readfds);  FD_SET(socket, &readfds);
			FD_ZERO(&errorfds); FD_SET(socket, &errorfds);
			select(socket+1, &readfds, 0, &errorfds, 0); // should block... not interested in writefds
			// if we have an error, return false
			if (FD_ISSET(socket, &errorfds))
			{
				GENERIK_TRACER;
				GENERIK_TRACE("postgres socket returned in errorfds");
				return false;
			}
			consume();
			return true;
		}
		
		PGnotify* notifies()
		{
			// mutex
			mutex.lock();
			PGnotify* notify = PQnotifies(connection);
			mutex.unlock();
			return notify;
		}

		void listen()
		{
			GENERIK_TRACER;
			
			while (running)
			{
				if (!waitforinput())
				{
					GENERIK_TRACE("received !waitforinput(); exiting...");
					break;
				}
				while (1)
				{
					PGnotify* notification = notifies();
					if (notification == 0) break;
					
					GENERIK_TRACE("received ["<<notification->relname<<"] from "<<notification->be_pid);
					raise(notification->relname);
					PQfreemem(notification);
				}
			}
		}
				
		bool parse_result(PGresult* result)
		{
			bool value = true;
			switch (PQresultStatus(result))
			{
				case PGRES_COMMAND_OK:
				case PGRES_TUPLES_OK:
				{
					// all ok
					break;
				}
				case PGRES_COPY_OUT:
				case PGRES_COPY_IN:
				{
					// all ok
					break;
				}
				case PGRES_EMPTY_QUERY:
				{
					// semi ok - probably an error
					GENERIK_TRACER;
					GENERIK_TRACE(PQresultErrorMessage(result));
					break;
				}
				case PGRES_BAD_RESPONSE:
				case PGRES_NONFATAL_ERROR:
				case PGRES_FATAL_ERROR:
				{
					// not ok!
					GENERIK_TRACER;
					GENERIK_ERROR(PQresultErrorMessage(result));
					value = false;
					break;
				}
				default:
				{
					GENERIK_TRACER;
					GENERIK_ERROR("unexpected reply from Postgres: "<<PQresultStatus(result));
					value = false;
				}
			}
			return value;
		}
		
		std::string make_path(const std::string& path_in)
		{
			if (!path_in.empty())
			{
				if (path_in[0] != '/')
				{
					return generik::getcwd() + "/" + path_in;
				}
			}
			return path_in;
		}

		void load_module(const std::string& path, const std::string& modulename)
		{
			GENERIK_TRACER;
			
			// add the absolute path to the dynamic_library_path
			std::string dynpath = make_path(path);
			GENERIK_TRACE_VALUE(dynpath);
			execute("set dynamic_library_path to '" + dynpath + "'");
			// load the module fresh
			execute("LOAD '" + modulename + "'");
			// register the get_register_functions() call
			execute("CREATE OR REPLACE FUNCTION get_register_functions() RETURNS text "
				"AS '" + modulename + "', 'dbspi_get_register_functions' "
				"LANGUAGE C STRICT");
			// use the call to get the SQL with which to register the functions in the module
			std::list<std::string> commands = query<std::string>("select * from get_register_functions()");
			for (std::list<std::string>::iterator i = commands.begin(); i != commands.end(); ++i)
			{
				// run the SQL
				execute(*i);
			}
		}
		
	
	};
	
}

#endif











